<template>
  <div>
    <van-nav-bar title="登录" />

    <van-form ref="checkout" @submit="login">
      <van-field
        placeholder="请输入手机号"
        v-model="user.mobile"
        :rules="checkout.mobile"
        name="iponp"
      >
        <i slot="left-icon" class="toutiao toutiao-shouji"></i>
      </van-field>
      <van-field
        placeholder="验证码"
        v-model="user.code"
        :rules="checkout.code"
      >
        <i slot="left-icon" class="toutiao toutiao-yanzhengma"></i>
        <template #button>
          <van-count-down
            :time="time"
            format="ss秒"
            v-if="!consoleDisplay"
            @finish="consoleDisplay = !consoleDisplay"
          />
          <van-button
            size="small"
            round
            native-type="button"
            @click="btn"
            v-else
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div class="box">
        <van-button block type="info" native-type="submit" :loading='loading' >登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { sendSms, longin } from "@/api/user";
export default {
  data() {
    return {
      user: {
        mobile: "",
        code: "",
      },
      //开始正则
      checkout: {
        mobile: [
          { pattern: /^1\d{10}$/, message: "请输入正确内容" },
          { required: true, message: "请输入手机号" },
        ],
        code: [
          { pattern: /^\d{6}$/, message: "请输入正确内容" },
          { required: true, message: "请输入验证码" },
        ],
      },
      //倒计时
      time: 6000,
      consoleDisplay: true,
      loading:false
    };
  },
  methods: {
    //点击验证码开始校验手机号输入框
    async btn() {
      await this.$refs.checkout.validate("iponp");
      //通过验证开始调验证码接口
      try {
        const res = await sendSms(this.user.mobile);
        //成功后开始搞个倒计时
        console.log("-------");
        this.$toast.success("验证码发送成功");
        this.consoleDisplay = !this.consoleDisplay;
      } catch (error) {
        if (error.response) {
          this.$toast.fail(error.response.data.message);
        } else {
          this.$toast.fail("网络有问题");
        }
      }
    },
    //登录事件
    async login() {
        this.loading=!this.loading
      try {
        const res = await longin(this.user);
        //要保存
        console.log(res)
        localStorage.setItem('token',res.data.data.token)
        this.$toast.success("开始跳转");
      } catch (error) {
        if (error.response) {
            console.log(error)
          this.$toast.fail(error.response.data.message);
        } else {
          this.$toast.fail("网络有问题");
        }
      }finally{
        this.loading=!this.loading
      }
    },
  },
};
</script>

<style scoped>
.box {
  margin: 16px;
}
</style>